package com.ytjj.quartz.service;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tencentyun.TLSSigAPIv2;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.service.RedisService;
import com.ytjj.qmyx.mall.mapper.LiveMapper;
import com.ytjj.qmyx.mall.model.Live;
import com.ytjj.qmyx.mall.model.LiveExample;
import com.ytjj.quartz.constants.LiveConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 直播服务
 * @ClassName LiveService
 *
 *
 * @Version 1.0
 **/

@Service
@Slf4j
public class LiveService {
    @Resource
    private LiveMapper liveMapper;
    @Resource
    private RedisService redisService;
    @Value("${quanmingyanxuan.usersig.sdkappid}")
    private long sdkappid;
    @Value("${quanmingyanxuan.usersig.key}")
    private String key;

    /**
     * 腾讯云直播检测
     */
    public void liveCheck() {
        LiveExample liveExample = new LiveExample();
        liveExample.createCriteria()
                .andStatusEqualTo(LiveConstant.LIVE_STATUS_ON)
                .andIsFakeEqualTo(LiveConstant.REAL_LIVE);
        List<Live> liveList = liveMapper.selectByExample(liveExample);
        if(liveList.size() > 0) {
            liveList.stream()
                    .forEach(item -> {
                        Date date = new Date();
                        // 关闭直播间
                        if(date.getTime() > item.getHeartbeatTime().getTime()) {
                            // 发送系统消息
                            this.sendSysMsg(item.getRoom());
                            // 修改直播间主播状态为下播
                            item.setStatus(LiveConstant.LIVE_STATUS_OFF);
                            this.destroyGroup(item.getRoom());
                            liveMapper.updateByPrimaryKeySelective(item);
                        } else {
                            // 获取直播间在线人数
                            String liveRoomHot = this.getLiveRoomHot(item.getRoom());
                            redisService.set(RedisConstants.LIVE_ONLINE_NUM + item.getId(), liveRoomHot);
                            redisService.expire(RedisConstants.LIVE_ONLINE_NUM + item.getId(), 24*60*60);
                        }
                    });
        }
    }

    /**
     * 腾讯云解散群
     */
    public void destroyGroup(String groupId) {
        String requestHost = "https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?";
        this.sendRequest(requestHost, groupId);
    }


    /**
     * 获取直播在线人数
     *
     * @param groupId
     * @return
     */
    public String getLiveRoomHot(String groupId) {
        String requestHost = "https://console.tim.qq.com/v4/group_open_http_svc/get_online_member_num?";
        JSONObject jsonObject = this.sendRequest(requestHost, groupId);
        String onlineMemberNum = jsonObject.getString("OnlineMemberNum");
        return onlineMemberNum;
    }

    /**
     * 解散群后发送的系统消息
     *
     * @param groupId
     */
    public void sendSysMsg(String groupId) {
        String requestHost = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification?";
        this.sendRequest(requestHost, groupId);
    }

    /**
     * 请求腾讯云API
     *
     * @param requestHost 请求
     * @param groupId 群id
     * @return
     */
    public JSONObject sendRequest(String requestHost, String groupId) {
        String sysMsg = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_system_notification?";
        TLSSigAPIv2 tlsSigAPIv2 = new TLSSigAPIv2(sdkappid, key);
        String userSig = tlsSigAPIv2.genSig("administrator", 100000000);
        String host = requestHost +
                "sdkappid=" +sdkappid+
                "&identifier=administrator" +
                "&usersig=" +userSig+
                "&random=" +RandomStringUtils.randomNumeric(32)+
                "&contenttype=json";
        Map<String, Object> map = new HashMap<>();
        map.put("GroupId", groupId);
        if(requestHost.equals(sysMsg)) {
            map.put("Content", "很遗憾，直播已下线！");
        }
        String result = HttpRequest.post(host)
                .body(JSON.toJSONString(map))
                .header("Content-Type","application/json; charset=UTF-8")
                .execute()
                .body();
        log.debug("result: {}", JSONObject.toJSONString(result, true));
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }



}
